package com.example.controller;

import com.example.shiro.AccountProfile;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 吕一明
 * @公众号 码客在线
 */
@Slf4j
@Controller
public class LoginController {

    @GetMapping("/login")
    public Object login() {
        return "login";
    }

    @PostMapping("/submit")
    public Object submit(String username, String password) {

        log.info("username-->{}, password-->{}", username, password);

        UsernamePasswordToken token = new UsernamePasswordToken();
        token.setUsername(username);
        token.setPassword(password.toCharArray());
        token.setRememberMe(true);

        SecurityUtils.getSubject().login(token);


        return "redirect:/index";
    }

    @GetMapping("/index")
    public Object index(HttpServletRequest request) {
        Object principal = SecurityUtils.getSubject().getPrincipal();

        AccountProfile user = (AccountProfile) principal;

        request.setAttribute("username", user.getUsername());

//        SecurityUtils.getSubject().hasRole("admin");

        return "index";
    }

    @GetMapping("/unauth")
    public Object unauth() {
        return "unauth";
    }

}
